package com.sanq.product.utils;

import com.sanq.product.config.utils.date.DateUtil;
import com.sanq.product.config.utils.http.HttpUtil;
import com.sanq.product.config.utils.string.DigestUtil;
import com.sanq.product.config.utils.string.StringUtil;
import com.sanq.product.config.utils.web.PropUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by XieZhyan on 2019/4/5.
 */
@Component
public class SmsUtil {

    private static final String LOGIN_NAME = "15110148609";
    private static final String LOGIN_PWD = "a123456";
    private static String encode = "GB2312";

    @Value("${sms.url}")
    public String smsUrl;

    public static class Holder {
        public static final SmsUtil INSTALCE = new SmsUtil();
    }

    public static SmsUtil getInstance() {
        return Holder.INSTALCE;
    }

    /**
     * 发送验证码
     *
     * @param tel
     */
    public Map<String, String> sendSms(String tel, String code) {
        Map<String, String> map = null;
        String content = "验证码为：{code}，如非本人操作，请忽略本短信【享阅读】";
        try {
            String dateStr = DateUtil.date2Str(new Date(), "yyyy-MM-dd HH:mm:ss");
            content = content.replace("{code}", code);

            String url = smsUrl;
            url = url.replace("{name}", URLEncoder.encode(LOGIN_NAME, encode)).
                replace("{pwd}", DigestUtil.getInstance().md5(LOGIN_PWD + dateStr)).
                replace("{tel}", tel).
                replace("{content}", URLEncoder.encode(content, "GB2312")).
                replace("{time}", dateStr.replace(" ", "%20"));

            String result = HttpUtil.getInstance().get(url, null);

            if(StringUtil.isEmpty(result)) {
                return null;
            }

            map = new HashMap<>();
            for(String s : result.split("&")) {
                String[] ss = s.split("=");
                map.put(ss[0], URLDecoder.decode(ss[1], "UTF-8"));
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return map;
    }
}
